<template>
  <q-drawer :show-if-above="false" :width="width" bordered elevated overlay side="right" v-model="open" dark>
    <div class="fixed" :style="{ width: width + 'px' }">
      <div class="row items-center q-px-md">
        <h1 class="col text-subtitle1 text-bold text-primary long-content text-white" :title="title">
          {{ title }}
        </h1>
        <q-btn round flat icon="close" @click="onClose" />
      </div>
    </div>
    <div class="q-px-md" style="padding-top: 56px">
      <slot></slot>
    </div>
  </q-drawer>
</template>

<script lang="ts">
import { useIsDarkActive } from 'src/boot/app';
import { emitter, useEmitter } from 'src/emitter';
import { defineComponent, nextTick, ref } from 'vue';

export default defineComponent({
  name: 'app-drawer',

  props: {
    id: {
      type: String,
      required: true,
    },
    title: {
      type: String,
      required: true,
    },
    width: {
      type: Number,
      default: 400,
    },
  },

  emits: ['open', 'close'],

  setup(props, emits) {
    const isDarkActive = useIsDarkActive();

    const open = ref(false);

    const onClose = () => {
      emits.emit('close');
      emitter.emit('drawer', { close: true });
    };

    useEmitter('drawer', payload => {
      if (payload.close) {
        open.value = false;
        return;
      }
      if (props.id === payload.id) {
        open.value = true;
        nextTick(() => {
          emits.emit('open', payload.data);
        });
      } else {
        open.value = false;
      }
    });

    return { open, onClose, isDarkActive };
  },
});
</script>
